package example.book.ui;

import java.util.ArrayList;
import java.util.List;

public class Database {
    private static List<User> users = new ArrayList<>();
    private static List<Book> books = new ArrayList<>();

    static {
        // 初始化用户数据
        users.add(new User("admin", "admin123", "admin"));
        users.add(new User("user1", "user123", "user"));

        // 初始化图书数据
        books.add(new Book("B001", "Java编程思想", "Bruce Eckel"));
        books.add(new Book("B002", "Effective Java", "Joshua Bloch"));
        books.add(new Book("B003", "深入理解Java虚拟机", "周志明"));
    }

    public static User authenticate(String username, String password) {
        for (User user : users) {
            if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                return user;
            }
        }
        return null;
    }

    public static List<Book> getAllBooks() {
        return books;
    }

    public static void addBook(Book book) {
        books.add(book);
    }

    public static boolean borrowBook(String bookId) {
        for (Book book : books) {
            if (book.getId().equals(bookId) && book.isAvailable()) {
                book.setAvailable(false);
                return true;
            }
        }
        return false;
    }

    public static boolean returnBook(String bookId) {
        for (Book book : books) {
            if (book.getId().equals(bookId) && !book.isAvailable()) {
                book.setAvailable(true);
                return true;
            }
        }
        return false;
    }
}

